package com.aac.rfcrabbitmvc.dao.impl;

import com.aac.rfcrabbitmvc.dao.BaseDao;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@SuppressWarnings("unchecked")
@Repository
@Transactional
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<T> queryHQL(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        return query.list();
    }


    @Override
    public List<T> executeJDBCSqlQuery(String sql, Class clazz, List<String> params) {
        SQLQuery sqlQuery = getSession().createSQLQuery(sql);
        for(int i = 0; i < params.size(); i++){
            sqlQuery.setParameter(i, params.get(i));
        }
        return sqlQuery.addEntity(clazz).list();
    }

}
